package business

import (
	"gitee.com/smallow/srpc/infrastructure/conf"
	"gitee.com/smallow/srpc/infrastructure/model"
	"gorm.io/gorm"
	"time"
)

func SaveUser(user *model.Employee) error {
	if user.ID != 0 {
		t := time.Now().Format("2006-01-02 15:04:05")
		return conf.GetMysqlDB().Table((&model.Employee{}).TableName()).Where("id=? and app_id=?", user.ID, user.AppID).Updates(map[string]interface{}{
			"name":          user.Name,
			"phone":         user.Phone,
			"sex":           user.Sex,
			"age":           user.Age,
			"state":         user.State,
			"department_id": user.DepartmentId,
			"company_id":    user.CompanyId,
			"memo":          user.Memo,
			"update_at":     t,
		}).Error
	} else {
		err := conf.GetMysqlDB().Create(user).Error
		if err != nil {
			return err
		}
		return nil
	}
}

func PhoneExist(phone string) bool {
	var count int64
	conf.GetMysqlDB().Table("is_employee").Where("phone = ?", phone).Count(&count)
	if count > 0 {
		return true
	}
	return false
}

// 根据条件查找用户
func FindUser(where *model.Employee) (*model.Employee, error) {
	user := &model.Employee{}
	err := conf.GetMysqlDB().Where(where).First(user).Error
	return user, err
}

// 删除人员信息及其账号
func DeleteUser(where *model.Employee) error {
	err := conf.GetMysqlDB().Transaction(func(tx *gorm.DB) error {
		// 删人员账号
		err1 := tx.Where("body_id = ? and  app_id=? and body_type=2", where.ID, where.AppID).Delete(&model.Account{}).Error
		if err1 != nil {
			return err1
		}
		// 删人
		err2 := tx.Where("id = ? and  app_id=?", where.ID, where.AppID).Delete(&model.Employee{}).Error
		if err2 != nil {
			return err2
		}
		return nil
	})
	return err
}
